package cc.service.impl;

import cc.model.Student;
import cc.persistence.PersistenceException;
import cc.persistence.PersistenceService;
import cc.service.ServiceException;
import cc.service.StudentService;

import java.util.List;
import java.util.Optional;

/**
 * @Author firefly
 * @since 2018/11/25
 */
public class StudentServiceImpl implements StudentService {
    private PersistenceService persistenceService = PersistenceLoader.persistenceService;

    @Override
    public List<Student> list() throws ServiceException {
        try {
            return persistenceService.list(Student.class);
        } catch (PersistenceException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public Optional<Student> get(String id) throws ServiceException {
        try {
            return persistenceService.get(Student.class, id);
        } catch (PersistenceException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public void addStudent(Student student) throws ServiceException {
        try {
            persistenceService.save(student);
        } catch (PersistenceException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public void add(String id, String name, String group) throws ServiceException {
        addStudent(new Student(id,name,group));
    }

    @Override
    public void updateStudent(Student student) throws ServiceException {
        try {
            persistenceService.save(student);
        } catch (PersistenceException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public void update(String id, String name, String group) throws ServiceException {
        updateStudent(new Student(id,name,group));
    }

    @Override
    public void deleteStudent(Student student) throws ServiceException {
        try {
            persistenceService.del(Student.class, student.getId());
        } catch (PersistenceException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public void delete(String id) throws ServiceException {
        deleteStudent(new Student(id));
    }
}
